/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package DAO;

import java.sql.*;
import BEANS.Alumno;
import java.util.ArrayList;
import java.util.List;
/**
 *
 * @author garzo
 */
public class Conexion {

    private  Connection conexion;

    public void connect(){
        try{
            Class.forName("com.mysql.jdbc.Driver");
            conexion = DriverManager.getConnection("jdbc:mysql://localhost/prueba","root","");
            System.out.println("Conexion establecida");
        }catch(ClassNotFoundException e){
            System.out.println("No se encontro la clase");
        }catch(SQLException e){
            System.out.println("Hay error en la conexion");
        }catch(Exception e){
            System.out.println("Error");
        }
    }

    public int getMax()throws SQLException{
        int idMax=0;
        PreparedStatement st=conexion.prepareStatement("SELECT max(id_alumno)FROM alumno");
        ResultSet rs = st.executeQuery();
        while(rs.next()){
            idMax=rs.getInt(1);
        }

        return idMax;
    }

    public void desconectar() throws SQLException{
        conexion.close();
        System.out.println("Conexion cerrada");
    }
    
    public void inserta(Alumno a) throws SQLException{
        PreparedStatement st = conexion.prepareStatement("INSERT INTO alumno value(?,?,?)"); /* prepareStatement va a ejecutar una sentencia sql*/
        st.setInt(1, getMax()+1);
        st.setString(2, a.getNombre());
        st.setString(3, a.getPass());
        st.executeUpdate(); /* ejecuta lo de sql*/
    }

    public List<Alumno> mostrarTodos() throws SQLException{
        List<Alumno> list=null;
        PreparedStatement st = conexion.prepareStatement("Select * from alumno");
        ResultSet rs=st.executeQuery(); /* ResultSet es el objeto que regresa executeQuery*/
        list=new ArrayList<Alumno>();

        while(rs.next()){
            list.add(new Alumno(rs.getInt(1),rs.getString(2),rs.getString(3)));
        }

        return list;

    }
}
